<?php
declare (strict_types = 1);

namespace app\backend\controller\data;

use app\backend\model\Admin;
use app\common\annotation\ControllerAnnotation;
use app\common\annotation\NodeAnnotation;
use app\common\model\Member;
use app\common\service\UploadService;
use think\App;
use think\facade\Cache;
use think\facade\Cookie;
use think\facade\Db;
use think\facade\Session;
use think\facade\View;
use think\helper\Str;
use think\queue\job\Redis;

/**
 * @ControllerAnnotation (title="爬虫数据")
 */
class Data extends \app\common\controller\Backend
{
    protected $pageSize = 15;
    protected $layout = 'layout/main';

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->modelClass = new \app\backend\model\Data();
        View::assign('statusList',$this->modelClass->getStatusList());

//        $companyList = CompanyCourse::query()->where('status', 1)->column('company_name', 'id');
    }


    /**
     * @NodeAnnotation(title="List")
     * @return \think\response\Json|\think\response\View
     */
    public function index()
    {
        if (request()->isAjax()) {
            if (request()->param('selectFields')) {
                $this->selectList();
            }
            list($this->page, $this->pageSize,$sort,$where,$tableName) = $this->buildParames();
            $list = $this->modelClass->where($where)->order($sort)->paginate([
                'list_rows'=> $this->pageSize,
                'page' => $this->page,
            ]);
            if(!empty($this->hiddenFields) ){
                foreach ($this->hiddenFields as $key=>$field){
                    $this->hiddenFields[$key] = $tableName.$field;
                }
                $list = $list->hidden($this->hiddenFields);
            }
            if(!empty($this->visibleFields) ){
                foreach ($this->visibleFields as $key=>$field){
                    $this->visibleFields[$key] = $tableName.$field;
                }
                $list = $list->visible($this->visibleFields);
            }
            $data = $list->items();
            /*foreach ($data as $k=>&$v){
                $v['get_time'] = '';
                $publish_time = str_replace('年', '-', $v['publish_time']);
                $publish_time = str_replace('月', '-', $publish_time);
                $publish_time = str_replace('日', '', $publish_time);
                $publish_time = strtotime($publish_time);
                if($publish_time){
                    $get_time = $this->calculateTime($publish_time);
                    $v['get_time'] = $get_time;
                }
            }*/
            $result = ['code' => 0, 'msg' => lang('Get Data Success'), 'data' => $data, 'count' =>$list->total()];
            return json($result);
        }
        return view();
    }

    public function calculateTime($publish_time)
    {
        // 假设你有一个时间戳
        $timestamp = $publish_time; // 这里使用当前时间，你可以根据需要替换为其他时间戳

        // 获取当前时间的时间戳
        $now = time();

        // 计算时间差
        $diff = $now - $timestamp;

        // 计算相差的分钟数
        $minutes = floor($diff / 60);

        // 计算相差的小时数
        $hours = floor($diff / 3600);

        // 计算相差的天数
        $days = floor($diff / 86400);

        if ($diff < 0) {
            return false;
        } elseif ($diff < 60) {
            return $diff.'秒前';
        } elseif ($diff < 3600) {
            return $minutes.'分钟前';
        } elseif ($diff < 86400) {
            return $hours.'小时前';
        } else {
            // 如果时间差大于24小时，显示日期和时间
            return $days.'天前';
            //echo date('Y-m-d H:i:s', $timestamp);
        }
    }

    /**
     * @NodeAnnotation(title="Import")
     * @return bool
     */
    public function import()
    {
        $file = request()->file('file');
        $file= UploadService::instance()->uploads(session('member.id'),session('amdin.id'));
        if(empty($file['url'])){
            $this->success(lang('刷新页面'));
        }
        $file = $file['url'];
        $excelData = $this->getFileData($file);
        if(!$excelData){
            $this->success(lang('刷新页面'));
        }
        $tableField = $this->getTableField();
        try {
            $excelData = array_filter($excelData);
            $fieldTitle = array_filter($excelData[0]);
            $data = [];
            $tableComment =  array_map('strtolower',array_values($tableField));
            $tableComment = array_map('trim', $tableComment);
            foreach ($excelData as $key => $value) {
                if($key == 0) continue;
                $one = [];
                foreach ($value as $k=>$val) {
                    if($k>count($fieldTitle)-1) unset($value[$k]);
                }
                $newValue = array_combine($fieldTitle,$value);
                foreach ($newValue as $k=>$v){
                    if(empty($v)){
                        continue;
                    }
                    if ($k && in_array(strtolower(trim($k)),$tableComment)) {
                        $field = array_search($k,$tableField);
                        if($this->importFields!=['*'] && !in_array($field,$this->importFields)) continue;
                        if($field=='admin_id' && is_string($v)){
                            $admin = Admin::where('username|realname',$v)->find();
                            if($admin){
                                $v = $admin->id;
                            }else{
                                $v = session('admin.id');
                            }
                        }
                        if($field=='member_id' && is_string($v)){
                            $admin = Member::where('username',$v)->find();
                            if($admin){
                                $v = $admin->id;
                            }else{
                                $v = session('member.id');
                            }
                        }
                        if($field){
                            $one[$field] = $v;
                        }

                    }
                }
                if($one) $data[] = $one;
            }
            $data = array_filter($data);
            if($data){
                foreach ($data as &$value) {
                    if(isset($value['confirm_status']) && $value['confirm_status']){
                        if($value['confirm_status'] == '未沟通'){
                            $value['confirm_status'] = 2;
                        }elseif ($value['confirm_status'] == '已沟通'){
                            $value['confirm_status'] = 1;
                        }
                    }

                }
            }
            $this->modelClass->saveAll($data);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success(lang('Import successful'));

    }

    /**
     * @NodeAnnotation(title="Export")
     */
    public function export()
    {
        $this->relationSearch = false;//关联表格，如果要关联需要单独重写
        list($this->page, $this->pageSize,$sort,$where) = $this->buildParames();
        $tableName = $this->modelClass->getName();
        $tableName  = Str::snake($tableName);
        $tablePrefix = $this->modelClass->get_table_prefix();
        $fieldList =  Cache::get($tableName.'_field');
        if(!$fieldList){
            $fieldList = Db::query("show full columns from {$tablePrefix}{$tableName}");
            Cache::tag($tableName)->set($tableName.'_field',$fieldList);
        }
        $tableInfo =  Cache::get($tableName);
        if(!$tableInfo){
            $tableInfo = Db::query("show table status like '{$tablePrefix}{$tableName}'");
            Cache::tag($tableName)->set($tableName,$tableInfo);
        }
        $headerArr = [];
        foreach ($fieldList as $vo) {
            if($this->exportFields !=['*'] && !in_array($vo['Field'],$this->exportFields)) continue;
            $comment = !empty($vo['Comment']) ? $vo['Comment'] : $vo['Field'];
            $comment = explode('=',$comment)[0];
            if(!in_array($vo['Field'],['update_time','create_time','delete_time','status','address4','manage_status','describe','area','address3','address2'])) {
                $headerArr[$vo['Field']] =$comment;
            } ;
        }
        $list = $this->modelClass->where($where)->field($this->exportFields)->order($sort)->select()->toArray();
        foreach ($list as &$value){
            if($value['confirm_status'] == 1){
                $value['confirm_status'] = '已沟通';
            }else{
                $value['confirm_status'] = '未沟通';
            }
        }
        $tableChName =  $tableInfo[0]['Comment']? $tableInfo[0]['Comment']:$tableName;
        $fileName = $tableChName.'-'.date('Y-m-d H:i:s').'.xlsx';
        $param  = [
            'headerArr'=>$headerArr,
            'fileName'=>$fileName,
            'list'=>$list,
        ];
        $res = hook_one('exportExcel',$param);
        if($res){
            $this->success(lang('export success'));
        }
        $this->excelData($list,$headerArr,$fileName);
    }

    /**
     * @NodeAnnotation(title="Detail")
     */
    public function detail()
    {
        $id = input('id');
        $this->modelClass->where('id',$id)->update([
            'confirm_status' => 1,
            'update_time' => time()
        ]);
        $this->success(lang("detail Success"));
    }

    public function test()
    {
    }

}

